package com.rr.springcloud.controller;

import com.rr.springcloud.lb.LoadBalancerImpl;
import com.rr.springcloud.pojo.Payment;
import com.rr.springcloud.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Objects;

/**
 * @author RR
 * @date 2021/3/15 12:30
 */
@RestController
public class OrderController {

    public static final String PAYMENT_URL = "http://PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private LoadBalancerImpl loadBalancer;

    @GetMapping("/consumer/payment/create")
    public ResultVo create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, ResultVo.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public ResultVo getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/" + id, ResultVo.class);
    }

    @GetMapping("/consumer/payment/getFoeEntity/{id}")
    public ResultVo getPaymentForEntity(@PathVariable("id")Long id){
        ResponseEntity<ResultVo> resultEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, ResultVo.class);
        if (resultEntity.getStatusCode().is2xxSuccessful()) {
            return resultEntity.getBody();
        }else {
            return new ResultVo(444, "操作错误");
        }
    }

    @GetMapping("/consumer/payment/lb")
    public String lb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-SERVICE");
        if (Objects.isNull(instances) || instances.size() == 0) {
            return "没有找到服务";
        }
        ServiceInstance instance = loadBalancer.getInstance(instances);
        URI uri = instance.getUri();

        return restTemplate.getForObject(uri + "/payment/lb", String.class);

    }
}
